package com.gwsdk.paysdk.utils;


import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


/**
 * 描述：打包写入的渠道信息相关工具类
 * 作者：闫冰
 * 时间: 2018-03-07 14:59
 */
public class GWPromoteUtils {

    private String launch_id;  //投放平台ID
    private String position;  //
    private int promote_game_version; //游戏版本号

    public GWPromoteUtils() {
        launch_id = "0";
        position = "1";
        promote_game_version = 0;
        String gameStr = getStr();
        if(!TextUtils.isEmpty(gameStr)){
            initJson(gameStr,"source_version");
            initJson(gameStr,"promote_id");
            initJson(gameStr,"launch_id");
            initJson(gameStr,"position");
            initJson(gameStr,"promote_account");
        }
    }



    public String getPosition() {
        return position;
    }

    public int getPromote_game_version() {
        return promote_game_version;
    }

    public String getLaunch_id() {
        return launch_id;
    }

    /**
     * 初始化
     *
     * @return
     */
    private void initJson(String jsonStr,String s) {
        try {
            JSONObject js = new JSONObject(jsonStr);
            if(s.equals("source_version")){
                promote_game_version = js.getInt("source_version");
            }
            if(s.equals("launch_id")){
                launch_id = js.getString("launch_id");
            }
            if(s.equals("position")){
                position = js.getString("position");
            }
        } catch (JSONException e) {
            GWLog.e("GWPromoteUtils Exception",e.toString());
            launch_id = "0";
        }
    }

    /**
     * 返回文件中字符串
     */
    private String getStr() {
        InputStream is = null;
        BufferedReader reader = null;
        String result = "";
        StringBuilder sb = new StringBuilder();
        String line = "";
        try {
            String ccfpath = "/META-INF/mch.properties";
            is = this.getClass().getResourceAsStream(ccfpath);
            reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            result = sb.toString();
        } catch (Exception e) {
            result = "";
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
            }
        }
        return result;
    }
}
